package com.ch.base.service;

import com.ch.base.dao.ChBasicOrderModelData;
import com.ch.base.enums.CodeEnum;
import com.ch.base.model.ChBasicOrderModel;
import com.ch.base.result.Result;
import com.ch.base.utils.FileUtil;
import com.ch.base.utils.OrderUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * created in 2019-04-19 10:57
 **/
@Slf4j
@Service
public class OrderService {

    @Resource
    private ChBasicOrderModelData orderData;
    @Resource
    private CommonService commonService;

    public Result<?> list(ChBasicOrderModel request) {

        log.info("start:find orders by[" + request + "]");
        int count = orderData.findCountByCondition(request);
        int[] page = commonService.getLimit(request.getPageIndex(), request.getPageSize());
        request.setLimit(page[0]);
        request.setLimitLen(page[1]);
        request.setOrderBy("order_time");
        List<ChBasicOrderModel> result = orderData.findOrdersByCondition(request);
        log.info("end:find" + count + "orders");
        return Result.createPage(result, (long) count);
    }

    public Result<?> upload(MultipartFile file) {

        log.info("start:upload[" + file.getOriginalFilename() + "]");
        List<Map<String, String>> data;
        try {
            data = FileUtil.processExcelOneSheet(file);
        } catch (Exception e) {
            log.error(e.getMessage());
            return Result.create(CodeEnum.FAIL.getCode(), "读取文件异常");
        }
        if (CollectionUtils.isEmpty(data)) {
            log.error("文件不能为空");
            return Result.create(CodeEnum.FAIL.getCode(), CodeEnum.FILE_UPLOAD_NULL.getMsg());
        }
        OrderUtil.check(data);
        List<ChBasicOrderModel> orders = OrderUtil.copyProperties(data);
        int i = orderData.batchInsertOrders(orders);
        log.info("end:upload[" + file.getOriginalFilename() + "]");
        return Result.create(CodeEnum.SUCCESS.getCode(), "成功导入订单[" + i + "]条");
    }
}
